package com.wangzeqi.changliaoba.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;

import com.wangzeqi.changliaoba.R;
import com.wangzeqi.changliaoba.base.ActivityCollector;
import com.wangzeqi.changliaoba.base.BaseActivity;
import com.wangzeqi.changliaoba.contacts.AddPersonActivity;
import com.wangzeqi.changliaoba.contacts.ContactsFragment;
import com.wangzeqi.changliaoba.worldlet.LiveFragment;

import com.wangzeqi.changliaoba.messege.MessegeFragment;
import com.wangzeqi.changliaoba.myself.MyselfFragment;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.Bmob;


/**
 * Created by dllo on 16/2/29.
 */
public class MainActivity extends BaseActivity {
    private ArrayList<Fragment> data;
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private MainViewPagerAdapter adapter;
    private TextView textView;

    private ImageButton imageViewBtn;

    List<Map<String, String>> moreList;
    private PopupWindow pwMyPopWindow;// popupwindow
    private ListView lvPopupList;// popupwindow中的ListView
    private int NUM_OF_VISIBLE_LIST_ROWS = 4;// 指定popupwindow中Item的数量

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCollector.addActivity(this);
        // 初始化 Bmob SDK
        // 使用时请将第二个参数Application ID替换成你在Bmob服务器端创建的Application ID
        Bmob.initialize(this, "f9f31294468a4470493d33d23bf13862");
        viewPager = (ViewPager) findViewById(R.id.main_vp);
        tabLayout = (TabLayout) findViewById(R.id.main_tl);
        imageViewBtn = (ImageButton) findViewById(R.id.more_btn);
        data = new ArrayList<>();
        data.add(new MessegeFragment());
        data.add(new ContactsFragment());
        data.add(new LiveFragment());
        data.add(new MyselfFragment());

//**
//
// 第三方服务器的存取
// */
//        ParseObject po = new ParseObject("Picture");
//        po.put("", im);
//
////        存文件  头像  语音
//        ParseFile pf = new ParseFile();
//        po.put("", pf);
//
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.chat_logo);
//        ByteArrayOutputStream stream = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
//        byte[] datass = stream.toByteArray();
//        final ParseFile imgeFile = new ParseFile("image.jpg",datass);
////        imgeFile.saveInBackground();
////            @Override
////            public void done(ParseException e) {
////                Log.d("MainActivity", "存储成共");
////                Log.d("MainActivity----", "e:" + e);
////            }
////        });
//        ParseObject po = new ParseObject("Picture");
//        po.put("tubiao", imgeFile);
//        po.saveInBackground(new SaveCallback() {
//            @Override
//            public void done(ParseException e) {
//                Log.d("MainActivity", "存储成共");
//                Log.d("MainActivity----", "e:" + e);
//            }
//        });
//
//
//
//        ParseQuery<ParseObject> pq = ParseQuery.getQuery("");
//        pq.getFirstInBackground(new GetCallback<ParseObject>() {
//            @Override
//            public void done(ParseObject object, ParseException e) {
//                ParseFile file = object.getParseFile("");
//                file.getDataInBackground(new GetDataCallback() {
//                    @Override
//                    public void done(byte[] data, ParseException e) {
//                      Bitmap bitmap1 = BitmapFactory.decodeByteArray(data,0,data);
//                        imageView.setImageBitmap(bitmap1);
//                    }
//                });
//            }
////            String url =
//        });
////存取回调
//        po.saveInBackground(new SaveCallback() {
//            @Override
//            public void done(ParseException e) {
//
//            }
//        });
//


        adapter = new MainViewPagerAdapter(getSupportFragmentManager(), data, this);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(adapter.getTabView(i));
            }
        }
        tabLayout.getTabAt(0).getCustomView().findViewById(R.id.tablayout_iv).setBackgroundResource(R.drawable.message_blue);

        textView = (TextView) tabLayout.getTabAt(0).getCustomView().findViewById(R.id.tablayout_tv);
        textView.setTextColor(0xFF00B2EE);
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                if (tab.getPosition() != 0) {
                    tabLayout.getTabAt(0).getCustomView().findViewById(R.id.tablayout_iv).setBackgroundResource(R.drawable.message_gray);
                    textView.setTextColor(0xFFC1CDCD);

                } else {
                    tabLayout.getTabAt(0).getCustomView().findViewById(R.id.tablayout_iv).setBackgroundResource(R.drawable.message_blue);
                    textView.setTextColor(0xFF00B2EE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        iniData();

        iniPopupWindow();

        imageViewBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pwMyPopWindow.isShowing()) {

                    pwMyPopWindow.dismiss();// 关闭
                } else {

                    pwMyPopWindow.showAsDropDown(imageViewBtn, 17, 27);// 显示
                }

            }
        });

    }

    private void iniData() {

        moreList = new ArrayList<Map<String, String>>();
        Map<String, String> map;
        map = new HashMap<String, String>();
        map.put("share_key", "添加好友");
        moreList.add(map);
        map = new HashMap<String, String>();
        map.put("share_key", "发起群聊");
        moreList.add(map);
        map = new HashMap<String, String>();
        map.put("share_key", "我的收藏");
        moreList.add(map);
        map = new HashMap<String, String>();
        map.put("share_key", "来扫一扫");
        moreList.add(map);

    }

    private void iniPopupWindow() {

        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.task_detail_popupwindow, null);
        lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
        pwMyPopWindow = new PopupWindow(layout);
        pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件
        lvPopupList.setAdapter(new SimpleAdapter(MainActivity.this, moreList,
                R.layout.item_list_popupwindow, new String[]{"share_key"},
                new int[]{R.id.tv_list_item}));
        lvPopupList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    Intent intent = new Intent(MainActivity.this, AddPersonActivity.class);
                    startActivity(intent);
                } else if (position == 1) {
                    Toast.makeText(MainActivity.this,
                            moreList.get(position).get("share_key"),
                            Toast.LENGTH_SHORT).show();
                } else if (position == 2) {
                    Toast.makeText(MainActivity.this,
                            moreList.get(position).get("share_key"),
                            Toast.LENGTH_SHORT).show();
                }else if(position ==3){
                    Intent intent = new Intent(MainActivity.this,SimpleScannerActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 控制popupwindow的宽度和高度自适应
        lvPopupList.measure(View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED);
        pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth() + 20);
        pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 40)
                * NUM_OF_VISIBLE_LIST_ROWS);
        // 控制popupwindow点击屏幕其他地方消失
        pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(
                R.mipmap.bg_popupwindow));// 设置背景图片，不能在布局中设置，要通过代码来设置
        pwMyPopWindow.setOutsideTouchable(true);// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功
//        pwMyPopWindow.showAtLocation(this.findViewById(R.id.more_btn), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 20, 20);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMChatManager.getInstance().logout();
        ActivityCollector.removeActivity(this);
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
                onDestroy();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}


